// Sunghan Cho
// 301140084
// sunghanc@sfu.ca

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "itemlistmodel.h"
#include "course.h"
#include "student.h"

#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(ItemManager *pCourses, ItemManager *pStudents, QWidget *parent)
	: QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	ui->courseTable->setDescription("All courses:");
	ui->allStudentTable->setDescription("Students in selected course:");
	ui->repeatStudentTable->setDescription("Repeat students in selected course:");

	// Connect open button to callback:
	QObject::connect(ui->btnAddFromFile, SIGNAL(clicked()),
					 this, SLOT(clickedAddItems()));

	// Connect the debug dump to our slot:
	QObject::connect(ui->btnDebugDump, SIGNAL(clicked()),
					 this, SLOT(dumpModels()));

	// Model updates --> refresh statistics:
	// -----------------------------------------------
	m_pCourses = pCourses;
	m_pStudents = pStudents;
	QObject::connect(pCourses, SIGNAL(itemsChanged()),
					 this, SLOT(updateStatistics()));
	QObject::connect(pStudents, SIGNAL(itemsChanged()),
					 this, SLOT(updateStatistics()));
}

MainWindow::~MainWindow()
{
	delete ui;
}

void MainWindow::setListModels(ItemListModel *pCourseModel,
									ItemListModel *pStudentModel,
									ItemListModel *pRepeatStudentModel)
{
	if (pCourseModel != 0) {
		ui->courseTable->setModel(pCourseModel);
	}
	if (pStudentModel != 0) {
		ui->allStudentTable->setModel(pStudentModel);
	}
	if (pRepeatStudentModel != 0) {
		ui->repeatStudentTable->setModel(pRepeatStudentModel);
	}
}

void MainWindow::clickedAddItems()
{
	QString fileName = QFileDialog::getOpenFileName(this, "Select item file", "", "Item Files (*.csv)");
	if (fileName.length() > 0) {
		emit addItemsFromFile(fileName);
	}
}

void MainWindow::updateStatistics()
{
	QString strCourseCount = QString("%1").arg(m_pCourses->getItemCount());
	QString strStudentCount = QString("%1").arg(m_pStudents->getItemCount());
	QString strRepeatStudentCount = QString("%1").arg(countRepeatStudents());

	ui->txtNumCourses->setText(strCourseCount);
	ui->txtNumStudents->setText(strStudentCount);
	ui->txtNumRepeatStudents->setText(strRepeatStudentCount);
}

int MainWindow::countRepeatStudents()
{
	const int REPEAT_COURSE_COUNT = 2;
	int repeatStudentCount = 0;
	QListIterator<Item*> studentItr = m_pStudents->getIterator();
	while (studentItr.hasNext()) {
		Student *pStudent = dynamic_cast<Student*>(studentItr.next());
		Q_ASSERT(pStudent != 0);
		if (pStudent->getCoursesTakenCount() >= REPEAT_COURSE_COUNT) {
			repeatStudentCount++;
		}
	}
	return repeatStudentCount;
}

void MainWindow::dumpModels()
{
	qDebug() << "\n\nCourse Model:";
	qDebug() << "-------------";
	m_pCourses->debugDumpData();

	qDebug() << "\n\nStudent Model:";
	qDebug() << "--------------";
	m_pStudents->debugDumpData();

}
